package com.nbst.controller.base;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import com.nbst.comnutil.DESUtil;
import com.nbst.comnutil.NormalResult;
import com.nbst.comnutil.StringUtil;
import com.nbst.comnutil.Tools;
import com.nbst.dao.mapper.mes.UserMapper;
import com.nbst.model.base.Base;
import com.nbst.model.base.EnumLogName;
import com.nbst.model.base.User;
import com.nbst.myInterface.MyLog;
import com.nbst.service.base.IDepartmentService;
import com.nbst.service.base.IMenuService;
import com.nbst.service.base.IUserService;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import net.sf.json.JSONObject;

/**
 * @ClassName: UserController
 * @Description:用户管理Controller
 * @author 兵
 * @date 2017-8-16
 * 
 */
@RestController
@RequestMapping("/user")
public class UserController {
	@Autowired
	IUserService userservice;

	@Autowired
	IMenuService permissionsservice;

	@Autowired
	IDepartmentService departmentservice;

	@Autowired
	UserMapper userMapper;

	@PostMapping("/getSession.action")
	public Object getShiroSession() {
		Session session = SecurityUtils.getSubject().getSession();
		return session.getAttribute("user");
	}

	/**
	 * 根据条件查询供应商用户列表
	 * 
	 * @return Object
	 * @author King
	 * @date 2019年11月23日
	 */
	@PostMapping("/findSupplierUsers.action")
	public Object findSupplierUsers(User user, @RequestParam(required = false, defaultValue = "1") Integer offset,
			@RequestParam(required = false, defaultValue = "10") Integer row) {
		Map<String, Object> map = Tools.transBean2Map(user);
		map.put("supp", 1);
		return userservice.findByCondition1(map, offset, row);
	}

	/**
	 * 根据条件查询客户用户列表
	 * 
	 * @return Object
	 * @author King
	 * @date 2019年11月23日
	 */
	@PostMapping("/findCustomerUsers.action")
	public Object findCustomerUsers(User user, @RequestParam(required = false, defaultValue = "1") Integer offset,
			@RequestParam(required = false, defaultValue = "10") Integer row) {
		Map<String, Object> map = Tools.transBean2Map(user);
		map.put("org", 1);
		return userservice.findByCondition1(map, offset, row);
	}

	/**
	 * 停用账号
	 * 
	 * @param id
	 * @return Object
	 * @author King
	 * @date 2018年11月5日
	 */
	@MyLog(value = EnumLogName.停用账号)
	@PostMapping(value = "/stopAccout.action")
	public Object shopAccout(Integer id, Integer fStop) {
		User user = (User) SecurityUtils.getSubject().getPrincipal();
		User stopUser = new User();
		stopUser.setId(id);
		if (fStop == null) {
			stopUser.setfStop(0);
		} else {
			stopUser.setfStop(fStop);
		}
		return userservice.stopUser(stopUser);
	}

	/**
	 * 启用已被停用的账号
	 * 
	 * @param id
	 * @return Object
	 * @author King
	 * @date 2018年11月5日
	 */
	@MyLog(value = EnumLogName.启用帐号)
	@PostMapping(value = "/startAccout.action")
	public Object startAccout(Integer id) {
		User user = (User) SecurityUtils.getSubject().getPrincipal();
		User stopUser = new User();
		stopUser.setId(id);
		stopUser.setfStop(1);
		return userservice.stopUser(stopUser);
	}

	/**
	 * 
	 * @Title: updatePassword @Description: 修改用户密码 @param @param
	 *         record @param @param session @param @return @return
	 *         NormalResult @throws
	 */
	@MyLog(value = EnumLogName.修改密码)
	@PostMapping(value = "/updatePassword.action")
	// @RequiresPermissions(value = "/updatePassword")
	public NormalResult updatePassword(User record, HttpSession session) {
		User user = (User) session.getAttribute("user");
		if (user != null) {
			return userservice.updatePassword(record);
		} else {
			return new NormalResult("9999", "用户登录信息失效，请重新登录");
		}

	}

	/**
	 * 
	 * @Title: insertUser2Dep @Description: 新增用户代管部门(也可用来作维修人员负责的部门) @param @param
	 *         uId 用户id(如果是作维修人员负责的部门用的话uId用来接收维修人员的id) @param @param dIds
	 *         多个部门id拼接中间用","隔开 @param @return @return NormalResult @throws
	 */
	@MyLog(value = EnumLogName.授权代管部门)
	@PostMapping(value = "/insertUser2Dep.action")
	public NormalResult insertUser2Dep(Integer uId, String dIds) {
		return userservice.insertUser2Dep(uId, dIds);
	}

	/**
	 * 
	 * @Title: getDepartmentUserTree @Description: 获取用户与部门关系树 @param @return @return
	 *         Object @throws
	 */
	@PostMapping(value = "/getDepartmentUserTree.action")
	public Object getDepartmentUserTree(String sfwwxbm, HttpSession session) {
		Map<String, Object> map = new HashMap<>();
		User user = (User) session.getAttribute("user");
		map.put("flag", "1");
		// List<Base> dep = departmentservice.getDepartmentTree(map);
		List<Base> list = userservice.getDepartmentUserTree(map);
		/*
		 * for (Base base : list) { dep.add(base); }
		 */
		return list;
	}

	/**
	 * 
	 * @Title: getUserList @Description: 根据条件查询用户信息 @param @param
	 *         record @param @param offset @param @param row @param @param
	 *         session @param @return @return Object @throws
	 */
	@PostMapping(value = "/getUserList.action")
	public Object getUserList(User record, Integer offset, Integer row, HttpSession session) {
		User user = (User) SecurityUtils.getSubject().getPrincipal();
		Map<String, Object> map = Tools.transBean2Map(record);
		int total = userservice.count(map);
		if (offset != null) {
			map.put("offset", offset - 1);
			map.put("row", row);
		}
		List<User> list = userservice.findByCondition(map);
		if (list.size() == 1) {
			if (list.get(0).getErpUserId() == null) {
				list.get(0).setErpUserId(16394);
			}
		}
		if (record.getId() != null) {
			map.put("uId", record.getId());
		}
		List<Base> mlist = permissionsservice.getRolePermissionList(map);
		JSONObject json = new JSONObject();
		json.put("total", total);
		json.put("rows", list);
		json.put("menu", mlist);
		return json.toString();
	}

	/**
	 * 
	 * @Title: insert @Description: 新增用户信息 @param @param record @param @param
	 *         session @param @return @return NormalResult @throws
	 */
	@MyLog(value = EnumLogName.新增用户)
	@PostMapping(value = "/addNew.action")
	public NormalResult insert(User record, HttpSession session, String rIds, String dIds) {
		String[] ids = null;
		if (!StringUtil.isEmpty(rIds)) {
			ids = rIds.split(",");
			if (ids.length == 1) {
				if ("".equals(ids[0])) {
					ids = null;
				}
			}
		}
		User user = (User) session.getAttribute("user");
		if (user != null) {
			record.setfBiller(user.getId());
		}

		NormalResult result = userservice.insertSelective(record, ids);
		return result;

	}

	/**
	 * 
	 * @Title: update @Description: 修改用户信息（包括逻辑删除） @param @param
	 *         record @param @param session @param @return @return
	 *         NormalResult @throws
	 */
	@MyLog(value = EnumLogName.修改用户信息)
	@PostMapping(value = "/updateUser.action")
	public NormalResult update(User record, HttpSession session, String rIds, String dIds) {

		User user = (User) session.getAttribute("user");
		if (user != null) {
			record.setfBiller(user.getId());
		}

		String[] ids = new String[] {};
		if (!StringUtils.isEmpty(rIds)) {
			ids = rIds.split(",");
		}
		userservice.insertUser2Dep(record.getId(), dIds);
		return userservice.updateByPrimaryKeySelective(record, ids);

	}

	/**
	 * 删除用户
	 * 
	 * @param id
	 * @return NormalResult
	 * @author King
	 * @date 2018年11月13日
	 */
	@MyLog(value = EnumLogName.删除用户)
	@GetMapping(value = "/deleteUser.action")
	//@RequiresPermissions(value = { "user:deleteUser" })
	public NormalResult delete(Integer id) {
		Map<String, Object> map = new HashMap<>(8);
		map.put("id", id);
		List<User> users = userservice.findByCondition(map);
		if ("admin".equals(users.get(0).getAccount()) || "system".equals(users.get(0).getAccount())) {
			return new NormalResult("9999", "该帐号为系统帐号不支持删除");
		}
		users.get(0).setfClosed(0);
		return userservice.updateByPrimaryKeySelective(users.get(0), null);
	}

	/**
	 * 获取明文密码
	 * 
	 * @param id
	 * @return String
	 * @author King
	 * @date 2020年1月11日
	 */
	@PostMapping("passWord.action")
	public String getPassWord(Integer id) {
		Map<String, Object> map = new HashMap<>(8);
		map.put("id", id);
		List<User> users = userservice.findByCondition(map);
		String passWord = DESUtil.decrypt(users.get(0).getPassword());
		return passWord;
	}

}